﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.Configuration;
using System.Data;

namespace DotNet.Utilities
{
    public class DBHelper
    {
        #region 构造Connection
        private static readonly string connectionString = ConfigurationManager.ConnectionStrings["DBConnectionString"].ToString();

        public static SqlConnection Con
        {
            get
            {

                return new SqlConnection(connectionString);
            }
        }
        #endregion

        #region 用于普通查询
        /// <summary>
        /// 不带参数查询 返回SqlDataReader
        /// </summary>
        /// <param name="sql">执行的Sql语句</param>
        /// <returns>SqlDataReader</returns>
        public static SqlDataReader Select(string sql)
        {
            SqlCommand cmd = new SqlCommand(sql, Con);
            cmd.Connection.Open();
            return cmd.ExecuteReader(CommandBehavior.CloseConnection);
        }

        /// <summary>
        /// 带参数的查询 返回SqlDataReader
        /// </summary>
        /// <param name="sql">执行的查询Sql语句</param>
        /// <param name="pars">执行的参数的数组</param>
        /// <returns>SqlDataReader</returns>
        public static SqlDataReader Select(string sql, SqlParameter[] pars)
        {
            SqlCommand cmd = new SqlCommand(sql, Con);
            cmd.Parameters.AddRange(pars);
            cmd.Connection.Open();
            SqlDataReader reader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
            return reader;

        }

        /// <summary>
        /// 执行查询语句，返回DataSet
        /// </summary>
        /// <param name="sql">查询语句</param>
        /// <returns>DataSet</returns>
        public static DataSet SelectReturnDataSet(string sql)
        {
            SqlCommand cmd = new SqlCommand(sql, Con);
            DataSet ds = new DataSet();
            try
            {
                SqlDataAdapter dad = new SqlDataAdapter(cmd);
                dad.Fill(ds, "ds");
            }
            catch (System.Data.SqlClient.SqlException ex)
            {
                throw new Exception(ex.Message);
            }

            return ds;
        }

        /// <summary>
        /// 执行带参查询语句，返回DataSet
        /// </summary>
        /// <param name="sql">查询语句</param>
        /// <param name="pars">参数数组</param>
        /// <returns>DataSet</returns>
        public static DataSet SelectReturnDataSet(string sql, SqlParameter[] pars)
        {
            SqlCommand cmd = new SqlCommand(sql, Con);
            cmd.Parameters.AddRange(pars);
            DataSet ds = new DataSet();
            try
            {
                SqlDataAdapter dad = new SqlDataAdapter(cmd);
                dad.Fill(ds, "ds");
            }
            catch (System.Data.SqlClient.SqlException ex)
            {
                throw new Exception(ex.Message);
            }
            return ds;
        }
        #endregion

        #region 存储过程操作
        /// <summary>
        /// 执行查询的无参存储过程 返回SqlDataReader
        /// </summary>
        /// <param name="name">存储过程的名字</param>
        /// <returns></returns>
        public static SqlDataReader SelectByProcedure(string name)
        {
            SqlCommand cmd = new SqlCommand(name, Con);
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Connection.Open();
            return cmd.ExecuteReader(CommandBehavior.CloseConnection);

        }
        /// <summary>
        /// 执行查询的有参存储过程 返回SqlDataReader
        /// </summary>
        /// <param name="name">存储过程的名字</param>
        /// <param name="pars">构造参数的数组</param>
        /// <returns>SqlDataReader</returns>
        public static SqlDataReader SelectByProcedure(string name, SqlParameter[] pars)
        {
            SqlCommand cmd = new SqlCommand(name, Con);
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.AddRange(pars);
            cmd.Connection.Open();
            return cmd.ExecuteReader(CommandBehavior.CloseConnection);

        }

        /// <summary>
        /// 执行查询的无参存储过程，返回DataSet
        /// </summary>
        /// <param name="name">存储过程的名字</param>
        /// <returns>DataSet</returns>
        public static DataSet SelectReturnDataSetByProcedure(string name)
        {
            SqlCommand cmd = new SqlCommand(name, Con);
            cmd.CommandType = CommandType.StoredProcedure;
            DataSet ds = new DataSet();
            try
            {
                cmd.Connection.Open();
                SqlDataAdapter dad = new SqlDataAdapter(cmd);
                dad.Fill(ds, "ds");
            }
            catch (System.Data.SqlClient.SqlException ex)
            {
                throw new Exception(ex.Message);
            }
            finally
            {
                cmd.Connection.Close();
            }
            return ds;
        }

        /// <summary>
        /// 执行查询的有参存储过程，返回DataSet
        /// </summary>
        /// <param name="name">存储过程的名字</param>
        /// <param name="pars">参数数组</param>
        /// <returns>DataSet</returns>
        public static DataSet SelectReturnDataSetByProcedure(string name, SqlParameter[] pars)
        {
            SqlCommand cmd = new SqlCommand(name, Con);
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.AddRange(pars);
            DataSet ds = new DataSet();
            try
            {
                cmd.Connection.Open();
                SqlDataAdapter dad = new SqlDataAdapter(cmd);
                dad.Fill(ds, "ds");
            }
            catch (System.Data.SqlClient.SqlException ex)
            {
                throw new Exception(ex.Message);
            }
            finally
            {
                cmd.Connection.Close();
            }
            return ds;
        }

        /// <summary>
        /// 执行非查询的无参存储过程
        /// </summary>
        /// <param name="name">存储过程的名字</param>
        /// <returns>int</returns>
        public static int NoSelectByProcedure(string name)
        {
            SqlCommand cmd = new SqlCommand(name, Con);
            cmd.CommandType = CommandType.StoredProcedure;
            try
            {
                cmd.Connection.Open();
                int result = cmd.ExecuteNonQuery();
                return result;
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                cmd.Connection.Close();
                cmd.Dispose();
            }
        }
        /// <summary>
        /// 执行非查询的有参参存储过程
        /// </summary>
        /// <param name="name">存储过程的名字</param>
        /// <param name="pars">参数的数组</param>
        /// <returns>int</returns>
        public static int NoSelectByProcedure(string name, SqlParameter[] pars)
        {
            SqlCommand cmd = new SqlCommand(name, Con);
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.AddRange(pars);
            try
            {
                cmd.Connection.Open();
                int result = cmd.ExecuteNonQuery();
                return result;
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                cmd.Connection.Close();
                cmd.Dispose();
            }
        }


        #endregion

        #region  用于非查询操作

        /// <summary>
        /// 非查询的执行无参sql语句 
        /// </summary>
        /// <param name="sql">执行的sql语句</param>
        /// <returns></returns>
        public static int NoSelect(string sql)
        {
            SqlCommand cmd = new SqlCommand(sql, Con);
            try
            {
                cmd.Connection.Open();
                int result = cmd.ExecuteNonQuery();
                return result;
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                cmd.Connection.Close();
            }
        }
        /// <summary>
        /// 非查询的执行带参sql语句
        /// </summary>
        /// <param name="sql">执行的sql语句</param>
        /// <param name="pars">sql语句中的参数数组</param>
        /// <returns></returns>
        public static int NoSelect(string sql, SqlParameter[] pars)
        {
            SqlCommand cmd = new SqlCommand(sql, Con);
            cmd.Parameters.AddRange(pars);
            try
            {
                cmd.Connection.Open();
                int i = cmd.ExecuteNonQuery();
                return i;
            }
            catch (Exception)
            {
                return 0;
            }
            finally
            {
                cmd.Connection.Close();
            }

        }
        #endregion

        #region 扩展静态方法
        /// <summary>
        /// 执行多条SQL语句，实现数据库事务。
        /// </summary>
        /// <param name="SQLStringList">多条SQL语句</param>		
        public static int ExecuteSqlTran(List<String> SQLStringList)
        {
            SqlCommand cmd = new SqlCommand();
            cmd.Connection = Con;
            SqlTransaction tx = cmd.Connection.BeginTransaction();
            cmd.Transaction = tx;
            try
            {
                int count = 0;
                for (int n = 0; n < SQLStringList.Count; n++)
                {
                    string strsql = SQLStringList[n];
                    if (strsql.Trim().Length > 1)
                    {
                        cmd.CommandText = strsql;
                        count += cmd.ExecuteNonQuery();
                    }
                }
                tx.Commit();
                return count;
            }
            catch
            {
                tx.Rollback();
                return 0;
            }
        }

        /// <summary>
        /// 执行一条计算查询结果语句，返回查询结果（object）。
        /// </summary>
        /// <param name="SQLString">计算查询结果语句</param>
        /// <returns>查询结果（object）</returns>
        public static object GetSingle(string SQLString)
        {
            SqlCommand cmd = new SqlCommand(SQLString, Con);
            try
            {
                cmd.Connection.Open();
                object obj = cmd.ExecuteScalar();
                if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
                {
                    return null;
                }
                else
                {
                    return obj;
                }
            }
            catch (System.Data.SqlClient.SqlException e)
            {
                throw e;
            }
            finally
            {
                cmd.Connection.Close();
            }
        }
        public static object GetSingle(string SQLString, int Times)
        {
            SqlCommand cmd = new SqlCommand(SQLString, Con);
            try
            {
                cmd.Connection.Open();
                cmd.CommandTimeout = Times;
                object obj = cmd.ExecuteScalar();
                if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
                {
                    return null;
                }
                else
                {
                    return obj;
                }
            }
            catch (System.Data.SqlClient.SqlException e)
            {
                cmd.Connection.Close();
                cmd.CommandTimeout = Times;
                throw e;
            }
        }

        /// <summary>
        /// 执行一条带参数计算查询结果语句，返回查询结果（object）。
        /// </summary>
        /// <param name="SQLString">计算查询结果语句</param>
        /// <returns>查询结果（object）</returns>
        public static object GetSingle(string SQLString, SqlParameter[] pars)
        {
            SqlCommand cmd = new SqlCommand(SQLString, Con);
            cmd.Parameters.AddRange(pars);
            try
            {
                cmd.Connection.Open();
                object obj = cmd.ExecuteScalar();
                if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
                {
                    return null;
                }
                else
                {
                    return obj;
                }
            }
            catch (System.Data.SqlClient.SqlException e)
            {
                throw e;
            }
            finally
            {
                cmd.Connection.Close();
            }
        }
        public static object GetSingle(string SQLString, SqlParameter[] pars, int Times)
        {
            SqlCommand cmd = new SqlCommand(SQLString, Con);
            try
            {
                cmd.Connection.Open();
                cmd.CommandTimeout = Times;
                cmd.Parameters.AddRange(pars);
                object obj = cmd.ExecuteScalar();
                if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
                {
                    return null;
                }
                else
                {
                    return obj;
                }
            }
            catch (System.Data.SqlClient.SqlException e)
            {
                cmd.Connection.Close();
                cmd.CommandTimeout = Times;
                throw e;
            }
        }

        #endregion

        #region 公用方法
        /// <summary>
        /// 判断是否存在某表的某个字段
        /// </summary>
        /// <param name="tableName">表名称</param>
        /// <param name="columnName">列名称</param>
        /// <returns>是否存在</returns>
        public static bool ColumnExists(string tableName, string columnName)
        {
            string sql = "select count(1) from syscolumns where [id]=object_id('" + tableName + "') and [name]='" + columnName + "'";
            object res = GetSingle(sql);
            if (res == null)
            {
                return false;
            }
            return Convert.ToInt32(res) > 0;
        }
        public static int GetMaxID(string FieldName, string TableName)
        {
            string strsql = "select max(" + FieldName + ")+1 from " + TableName;
            object obj = DBHelper.GetSingle(strsql);
            if (obj == null)
            {
                return 1;
            }
            else
            {
                return int.Parse(obj.ToString());
            }
        }
        /// <summary>
        /// 是否是可执行sql语句
        /// </summary>
        /// <param name="strSql">执行的sql语句</param>
        /// <returns>Bool</returns>
        public static bool Exists(string strSql)
        {
            object obj = DBHelper.GetSingle(strSql);
            int cmdresult;
            if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
            {
                cmdresult = 0;
            }
            else
            {
                cmdresult = int.Parse(obj.ToString());
            }
            if (cmdresult == 0)
            {
                return false;
            }
            else
            {
                return true;
            }
        }
        /// <summary>
        /// 表是否存在
        /// </summary>
        /// <param name="TableName"></param>
        /// <returns></returns>
        public static bool TabExists(string TableName)
        {
            string strsql = "select count(*) from sysobjects where id = object_id(N'[" + TableName + "]') and OBJECTPROPERTY(id, N'IsUserTable') = 1";
            //string strsql = "SELECT count(*) FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[" + TableName + "]') AND type in (N'U')";
            object obj = DBHelper.GetSingle(strsql);
            int cmdresult;
            if (obj == null)
            {
                cmdresult = 0;
            }
            else
            {
                cmdresult = int.Parse(obj.ToString());
            }
            if (cmdresult == 0)
            {
                return false;
            }
            else
            {
                return true;
            }
        }
        public static bool Exists(string strSql, params SqlParameter[] cmdParms)
        {
            object obj = DBHelper.GetSingle(strSql, cmdParms);
            int cmdresult;
            if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
            {
                cmdresult = 0;
            }
            else
            {
                cmdresult = int.Parse(obj.ToString());
            }
            if (cmdresult == 0)
            {
                return false;
            }
            else
            {
                return true;
            }
        }
        #endregion

        public static bool AddByTran(string sql, SqlParameter[] pars)
        {
            SqlCommand cmd = new SqlCommand(sql, Con);
            //cmd.CommandType = CommandType.StoredProcedure;

            cmd.Parameters.AddRange(pars);

            cmd.Connection.Open();
            SqlTransaction tran = cmd.Connection.BeginTransaction();
            cmd.Transaction = tran;//开启一个事务

            try
            {
                cmd.ExecuteNonQuery();
            }
            catch (Exception)
            {
                tran.Rollback();
                cmd.Connection.Close();
                return false;
                throw;
            }
            tran.Commit();
            return true;
        }
        public static object GetIdByCondition(string sql, SqlParameter[] pars)
        {
            SqlCommand cmd = new SqlCommand(sql, Con);
            cmd.Parameters.AddRange(pars);
            cmd.Connection.Open();
            object result = cmd.ExecuteScalar();
            cmd.Connection.Close();
            return result;
        }

        #region 返回多个集合
        /// <summary>
        /// add:zhaohh 2014-01-06
        /// 返回多个集合时
        /// </summary>
        /// <param name="command">存储过程名</param>
        /// <param name="index">返回指定的集合</param>
        /// <param name="paras">参数</param>
        /// <returns></returns>
        public DataTable RunSPGetDataSet(string command, int index, params object[] paras)
        {
            SqlDataAdapter adapter = new SqlDataAdapter();
            SqlConnection con = Con;
            using (SqlCommand cmd = new SqlCommand(command, con))
            {
                adapter.SelectCommand = cmd;
                cmd.CommandTimeout = 2400;
                cmd.CommandType = CommandType.StoredProcedure;

                if (paras != null)
                {
                    cmd.Parameters.AddRange(paras);
                }
                DataSet ds = new DataSet();
                DataTable table = new DataTable();
                adapter.Fill(ds);
                adapter.SelectCommand.Parameters.Clear();

                return ds.Tables[index];
            }
        } 
        #endregion

        #region 返回单个集合时
        /// <summary>
        /// add:zhaohh 2014-01-06
        /// 返回单个集合时
        /// </summary>
        /// <param name="command">存储过程名</param>
        /// <param name="paras">参数</param>
        /// <returns></returns>
        public DataSet RunSPGetDataSet(string command, params object[] paras)
        {
            SqlDataAdapter adapter = new SqlDataAdapter();
            SqlConnection con = Con;
            using (SqlCommand cmd = new SqlCommand(command, con))
            {
                adapter.SelectCommand = cmd;
                cmd.CommandTimeout = 2400;
                cmd.CommandType = CommandType.StoredProcedure;

                if (paras != null)
                {
                    cmd.Parameters.AddRange(paras);
                }
                DataSet ds = new DataSet();
                adapter.Fill(ds);
                adapter.SelectCommand.Parameters.Clear();

                return ds;
            }
        } 
        #endregion


    }
}
